const Article = require('../../models/article')
const Tag = require('../../models/tag')
const User = require('../../models/user')

module.exports = (req, res) => {
  var formData = {}
  req.body.tag = JSON.parse(req.body.tag)
  formData.title = req.body.title
  formData.author = req.body.author
  formData.tag = req.body.tag
  formData.content = req.body.content
  formData.created_time = new Date
  formData.last_modified_time = new Date
  // console.log(formData)

  User.findOne({username:formData.author},(err,userDoc) => {
    userDoc.articleNum = parseInt(userDoc.articleNum) + 1
    userDoc.articleNum = userDoc.articleNum.toString()
    // console.log(userDoc.articleNum);
    User.findOneAndUpdate({username:formData.author},userDoc,(err,newUserDoc) => {
      console.log('scuess');
    })
  })


  // 修改标签下的文章数量
  // formData.tag []
  const tag_id = '62162ed14c4270244c5f60db'
  var fatherArr = []
  var sonArr = formData.tag
  Tag.findById({ _id: tag_id }, (err, tagDoc) => {
    if (err) {
      return res.status(500).json({
        err_code: 500,
        message: err.message
      })
    }
    // [{},{},{}] 父数组
    fatherArr = tagDoc.tags
    for (let i = 0; i < sonArr.length; i++) {
      // sonArr[i].tag_name
      // fatherArr[i].tag_name
      const item_i = sonArr[i]
      for (let j = 0; j < fatherArr.length; j++) {
        const item_j = fatherArr[j];
        if (item_i.tag_name === item_j.tag_name) {
          // console.log(j);
          item_j.tag_number = parseInt(item_j.tag_number) + 1
          item_j.tag_number.toString()
          console.log(item_j.tag_name + ':' + item_j.tag_number);
          // [] --- 
          formData.tag[i].tag_number = item_j.tag_number

        }
      }
    }
    // console.log(fatherArr);
    Tag.findByIdAndUpdate({_id:tag_id},{tags:fatherArr},(err,newTagDoc) => {
      if (err) {
        return res.status(500).json({
          err_code: 500,
          message: 'Tag的错误:' + err.message
        })
      }
    })

    new Article(formData).save((err, articleDoc) => {
      if (err) {
        return res.status(500).json({
          err_code: 500,
          message: 'Article的错误:' +err.message
        })
      }
      // 创建成功
      res.status(200).json({
        err_code: 0,
        message: '文章发布成功'
      })
    })
  })
}